import { siteConfig } from '../config/site'
import { ref, watch } from 'vue'
import { useStorage } from '@vueuse/core'
import { validateConfig, validateConfigItem } from './configValidator'

const CACHE_KEY = 'site_config_cache'
const CACHE_DURATION = 24 * 60 * 60 * 1000 // 24小时
const CONFIG_VERSION = '1.0.0' // 配置版本号

class ConfigError extends Error {
  constructor(message, errors = null) {
    super(message)
    this.name = 'ConfigError'
    this.errors = errors
  }
}

const configRef = ref(null)

export function useConfig(key) {
  try {
    // 验证配置版本
    validateConfigVersion()
    
    // 尝试从缓存获取
    const cached = getCachedConfig()
    if (cached) {
      const value = getValueByKey(cached, key)
      console.log(`Getting ${key} from cache:`, value)
      // 验证获取的值
      const { valid, errors } = validateConfigItem(key, value)
      if (!valid) {
        throw new ConfigError(`Invalid cached config for key: ${key}`, errors)
      }
      return value
    }

    // 使用默认配置
    const value = getValueByKey(siteConfig, key)
    console.log(`Getting ${key} from default config:`, value)
    // 验证获取的值
    const { valid, errors } = validateConfigItem(key, value)
    if (!valid) {
      throw new ConfigError(`Invalid default config for key: ${key}`, errors)
    }
    
    // 缓存配置
    cacheConfig(siteConfig)
    
    return value
  } catch (err) {
    console.error('Config error:', err)
    // 返回原始配置
    return getValueByKey(siteConfig, key)
  }
}

export function useConfigWithHotReload() {
  // 监听配置变化
  watch(() => configRef.value, (newConfig) => {
    if (newConfig) {
      cacheConfig(newConfig)
      // 可以添加通知或其他处理
    }
  })
  
  return configRef
}

// 添加配置热重载
export function setupConfigHotReload() {
  if (import.meta.hot) {
    import.meta.hot.accept(['../config/site.js'], ([newSiteConfig]) => {
      if (newSiteConfig) {
        // 更新配置
        const stored = useStorage('site_config', newSiteConfig.siteConfig)
        stored.value = newSiteConfig.siteConfig
      }
    })
  }
}

function getValueByKey(obj, key) {
  try {
    const keys = key.split('.')
    let value = obj
    
    for (const k of keys) {
      value = value[k]
      if (value === undefined) {
        console.warn(`Config key "${key}" not found`)
        return null
      }
    }
    
    return value
  } catch (err) {
    console.error('Error getting config value:', err)
    return null
  }
}

function getCachedConfig() {
  try {
    const cached = localStorage.getItem(CACHE_KEY)
    if (!cached) return null
    
    const { timestamp, data, version } = JSON.parse(cached)
    
    // 检查版本
    if (version !== CONFIG_VERSION) {
      clearCache()
      return null
    }
    
    // 检查过期时间
    if (Date.now() - timestamp > CACHE_DURATION) {
      clearCache()
      return null
    }
    
    return data
  } catch (err) {
    console.warn('Failed to get cached config:', err)
    return null
  }
}

function cacheConfig(config) {
  try {
    const cache = {
      timestamp: Date.now(),
      version: CONFIG_VERSION,
      data: config
    }
    localStorage.setItem(CACHE_KEY, JSON.stringify(cache))
  } catch (err) {
    console.warn('Failed to cache config:', err)
  }
}

// 验证配置版本
function validateConfigVersion() {
  const cached = localStorage.getItem(CACHE_KEY)
  if (cached) {
    const { version } = JSON.parse(cached)
    if (version !== CONFIG_VERSION) {
      clearCache()
    }
  }
}

// 清除缓存
function clearCache() {
  try {
    localStorage.removeItem(CACHE_KEY)
  } catch (err) {
    console.warn('Failed to clear config cache:', err)
  }
}

// 更新缓存
function updateCache(newConfig) {
  try {
    const { valid, errors } = validateConfig(newConfig)
    if (!valid) {
      throw new ConfigError('Invalid config update', errors)
    }
    cacheConfig(newConfig)
  } catch (err) {
    console.error('Failed to update config:', err)
    throw err
  }
}

// 获取配置版本
function getVersion() {
  return CONFIG_VERSION
} 